package com.iflytek.crvoice2txt.model;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;

import com.iflytek.cloud.ErrorCode;
import com.iflytek.cloud.InitListener;
import com.iflytek.cloud.RecognizerListener;
import com.iflytek.cloud.RecognizerResult;
import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.SpeechRecognizer;
import com.iflytek.cloud.ui.RecognizerDialog;
import com.iflytek.crvoice2txt.application.MyApplication;
import com.iflytek.crvoice2txt.constant.IatSetting;
import com.iflytek.crvoice2txt.database.RecordOperation;
import com.iflytek.crvoice2txt.entity.RecorderEntity;
import com.iflytek.crvoice2txt.present.RecoderSignPresent;
import com.iflytek.crvoice2txt.util.AudioUtil;
import com.iflytek.crvoice2txt.util.Count60S;
import com.iflytek.crvoice2txt.util.DateUtil;
import com.iflytek.crvoice2txt.util.FileUtil;
import com.iflytek.crvoice2txt.util.JsonParser;
import com.iflytek.sunflower.FlowerCollector;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;

import rx.Observable;
import rx.Observer;
import rx.Scheduler;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

import static com.iflytek.crvoice2txt.constant.IatSetting.TEXT_PATH_HEAD;

public class RecordSignBizImpl implements RecordSignBiz {

    private static final String TAG = "RecordSignBizImpl";

    private String AUDIO_SAVE_PATH;

    private Context context;

    private RecorderEntity mRecorderEntity;
    // 语音听写对象
    private SpeechRecognizer mIat;
    // 语音听写UI
    private RecognizerDialog mIatDialog;
    // 用HashMap存储听写结果
    private HashMap<String, String> mIatResults = new LinkedHashMap<String, String>();

    private SharedPreferences mSharedPreferences;
    // 引擎类型
    private String mEngineType = SpeechConstant.TYPE_CLOUD;

    private RecoderSignPresent.OnVoiceDictationFinished onVoiceDictationFinished;

    private Count60S count60S;

    private RecordOperation recordOperation;

    private Date signDate;//记录按下开始录音时的时间，也就是音频预保存的路径（由时间组成）

    private int audioLong;//本次录音的时长

    private StringBuilder stringBuilder;//本次录音文本

    private AudioUtil audioUtil;//播放声音

    public RecordSignBizImpl(Context context, RecoderSignPresent.OnVoiceDictationFinished onVoiceDictationFinished) {
        this.context = context;
        this.onVoiceDictationFinished = onVoiceDictationFinished;
        initData();
    }

    @Override
    public void initData() {

        stringBuilder = new StringBuilder();
        AUDIO_SAVE_PATH = Environment.getExternalStorageDirectory() + "/msc/iat.wav";
        audioUtil = new AudioUtil();
        count60S = new Count60S(onVoiceDictationFinished);
        // 使用SpeechRecognizer对象，可根据回调消息自定义界面；
        mIat = SpeechRecognizer.createRecognizer(context, mInitListener);
        // 初始化听写Dialog，如果只使用有UI听写功能，无需创建SpeechRecognizer
        // 使用UI听写功能，请根据sdk文件目录下的notice.txt,放置布局文件和图片资源
        mSharedPreferences = context.getSharedPreferences(IatSetting.PREFER_NAME, Activity.MODE_PRIVATE);
        recordOperation = new RecordOperation(onVoiceDictationFinished);
    }

    /**
     * 初始化监听器。
     */
    private InitListener mInitListener = new InitListener() {

        @Override
        public void onInit(int code) {
            Log.d(TAG, "初始化失败，错误码：SpeechRecognizer init() code = " + code);
            if (code != ErrorCode.SUCCESS) {
                onVoiceDictationFinished.showToast("初始化失败！");
            }
        }
    };

    /**
     * 听写监听器。
     */
    private RecognizerListener mRecognizerListener = new RecognizerListener() {

        @Override
        public void onBeginOfSpeech() {
            // 此回调表示：sdk内部录音机已经准备好了，用户可以开始语音输入
            //onVoiceDictationFinished.showToast("开始说话");
            count60S.start();
        }

        @Override
        public void onError(SpeechError error) {
            // Tips：
            // 错误码：10118(您没有说话)，可能是录音机权限被禁，需要提示用户打开应用的录音权限。
            Log.i("lplplplp", error.getErrorCode() + "");
            if (error.getErrorCode() == 14002) {
                onVoiceDictationFinished.showToast(error.getPlainDescription(true) + "\n请确认是否已开通翻译功能");
            } else if (error.getErrorCode() == 20999) {
                onVoiceDictationFinished.showToast("未知错误");
            } else {
                onVoiceDictationFinished.showToast("没听请您在说什么");
            }
        }

        @Override
        public void onEndOfSpeech() {
            // 此回调表示：检测到了语音的尾端点，已经进入识别过程，不再接受语音输入
            //onVoiceDictationFinished.showToast("结束说话");
            Observable.create(new Observable.OnSubscribe<String>() {
                @Override
                public void call(Subscriber<? super String> subscriber) {
                    String timelong = FileUtil.getRingDuring(AUDIO_SAVE_PATH);
                    subscriber.onNext(timelong);
                    subscriber.onCompleted();
                }
            }).subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Observer<String>() {
                        @Override
                        public void onCompleted() {
                        }

                        @Override
                        public void onError(Throwable e) {
                        }

                        @Override
                        public void onNext(String b) {
                            onVoiceDictationFinished.dicationFinished(getRecorderEntity());
                        }
                    });
        }

        @Override
        public void onResult(RecognizerResult results, boolean isLast) {
            Log.d(TAG, "results.getResultString():" + results.getResultString());
            printResult(results, false);
            if (isLast) {
                // TODO 最后的结果
                if (onVoiceDictationFinished != null) {
                    onVoiceDictationFinished.dicationFinished(getRecorderEntity());
                }
            }
        }

        @Override
        public void onVolumeChanged(int volume, byte[] data) {
            //onVoiceDictationFinished.showToast("当前正在说话，音量大小：" + volume);
        }

        @Override
        public void onEvent(int eventType, int arg1, int arg2, Bundle obj) {
            // 以下代码用于获取与云端的会话id，当业务出错时将会话id提供给技术支持人员，可用于查询会话日志，定位出错原因
            // 若使用本地能力，会话id为null
            //	if (SpeechEvent.EVENT_SESSION_ID == eventType) {
            //		String sid = obj.getString(SpeechEvent.KEY_EVENT_SESSION_ID);
            //		Log.d(TAG, "session id =" + sid);
            //	}
        }
    };

    @Override
    public void startVoiceDictation() {
        stringBuilder.delete(0, stringBuilder.length());
        signDate = DateUtil.getCurrentDate();
        String datestr = DateUtil.DateToStr(signDate, DateUtil.DF_YYYY_MM_DD_HH_MM_SS_WAV);
        AUDIO_SAVE_PATH = Environment.getExternalStorageDirectory() + "/msc/会议纪要录音/" + datestr + ".wav";
        FlowerCollector.onEvent(context, "iat_recognize");
        mIatResults.clear();
        setParam();
        // 不显示听写对话框
        int ret = mIat.startListening(mRecognizerListener);
        if (ret != ErrorCode.SUCCESS) {
            onVoiceDictationFinished.showToast("听写失败,错误码：" + ret);
        }
    }

    @Override
    public void stopVoiceDictation() {
        mIat.stopListening();
        count60S.stop();
    }

    @Override
    public void cancelVoiceDictation() {
        mIat.cancel();
    }

    @Override
    public void printResult(RecognizerResult results, boolean flag) {

        String text = JsonParser.parseIatResult(results.getResultString());
        String sn = null;
        // 读取json结果中的sn字段
        try {
            JSONObject resultJson = new JSONObject(results.getResultString());
            sn = resultJson.optString("sn");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        mIatResults.put(sn, text);
        StringBuffer resultBuffer = new StringBuffer();
        for (String key : mIatResults.keySet()) {
            resultBuffer.append(mIatResults.get(key));
        }
        Log.i("777777777777777777777", "777777777" + resultBuffer.toString());
        stringBuilder.append(resultBuffer.toString());
    }

    @Override
    public void onResume() {
        // 开放统计 移动数据统计分析
        FlowerCollector.onResume(context);
        FlowerCollector.onPageStart(TAG);
    }

    @Override
    public void onPause() {
        // 开放统计 移动数据统计分析
        FlowerCollector.onPageEnd(TAG);
        FlowerCollector.onPause(context);
    }

    @Override
    public void onDestroy() {
        if (audioUtil != null) {
            audioUtil.release();
        }
        if (null != recordOperation) {
            recordOperation.closeRealm();
        }
        if (null != mIat) {
            // 退出时释放连接
            mIat.cancel();
            mIat.destroy();
        }
    }

    @Override
    public void saveText(RecorderEntity recorderEntity) {
        mRecorderEntity = recorderEntity;
        Observable.create(new Observable.OnSubscribe<Boolean>() {
            @Override
            public void call(Subscriber<? super Boolean> subscriber) {
                boolean bl = FileUtil.writeTxtToFile(mRecorderEntity.text, TEXT_PATH_HEAD, mRecorderEntity.name);
                if (!bl) {
                    subscriber.onNext(false);
                    subscriber.onCompleted();
                } else {
                    mRecorderEntity.size = FileUtil.getFileSize(mRecorderEntity.txt_path + mRecorderEntity.name);
                    subscriber.onNext(true);
                    subscriber.onCompleted();
                }
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Boolean>() {
                    @Override
                    public void onCompleted() {
                    }

                    @Override
                    public void onError(Throwable e) {
                    }

                    @Override
                    public void onNext(Boolean b) {
                        if (b) {
                            Log.i(TAG, "mRe:" + mRecorderEntity.toString());
                            recordOperation.insertAsyn(mRecorderEntity);
                        } else {
                            onVoiceDictationFinished.saveTextToDbFinished(false);
                        }
                    }
                });
    }

    private RecorderEntity getRecorderEntity() {
        RecorderEntity mRecorderEntity = new RecorderEntity();
        String datestr = DateUtil.DateToStr(signDate, DateUtil.DF_YYYY_MM_DD_HH_MM_SS);
        String timeDesc = DateUtil.DateToStr(signDate, DateUtil.DF_YYYY_MM_DD_HH_MM_SS_DESC);
        mRecorderEntity.name = timeDesc + ".txt";
        mRecorderEntity.type = 0;
        mRecorderEntity.text = stringBuilder.toString();
        mRecorderEntity.date = signDate;
        mRecorderEntity.audio_path = AUDIO_SAVE_PATH;
        mRecorderEntity.timelong = count60S.timelong;
        mRecorderEntity.dateStr = DateUtil.DateToStr(signDate, DateUtil.DF_YYYY_MM_DD_HH_MM_SS);
        mRecorderEntity.txt_path = TEXT_PATH_HEAD;
        Log.i("777777777777777777777", "777777777" + mRecorderEntity.toString());
        return mRecorderEntity;
    }

    @Override
    public void startPlayAudio(final String path) {
        audioUtil.startPlay(path);
    }

    @Override
    public void stopPlayAudio() {
        audioUtil.stopPlay();
    }

    /**
     * 获取数据初始化会议记录界面的信息记录
     */
    @Override
    public void getSaveList() {
        recordOperation.queryAllAsyn();
    }

    /**
     * 参数设置
     *
     * @return
     */
    public void setParam() {

        // 清空参数
        mIat.setParameter(SpeechConstant.PARAMS, null);
        // 设置听写引擎
        mIat.setParameter(SpeechConstant.ENGINE_TYPE, mEngineType);
        // 设置返回结果格式
        mIat.setParameter(SpeechConstant.RESULT_TYPE, "json");
        String lag = "mandarin";//mSharedPreferences.getString("iat_language_preference", "mandarin");
        if (lag.equals("en_us")) {
            // 设置语言
            mIat.setParameter(SpeechConstant.LANGUAGE, "en_us");
            mIat.setParameter(SpeechConstant.ACCENT, null);
        } else {
            // 设置语言
            mIat.setParameter(SpeechConstant.LANGUAGE, "zh_cn");
            // 设置语言区域
            mIat.setParameter(SpeechConstant.ACCENT, lag);
        }
        //此处用于设置dialog中不显示错误码信息
        //mIat.setParameter("view_tips_plain","false");
        // 设置语音前端点:静音超时时间，即用户多长时间不说话则当做超时处理
        mIat.setParameter(SpeechConstant.VAD_BOS, mSharedPreferences.getString("iat_vadbos_preference", "59000"));
        // 设置语音后端点:后端点静音检测时间，即用户停止说话多长时间内即认为不再输入， 自动停止录音
        mIat.setParameter(SpeechConstant.VAD_EOS, mSharedPreferences.getString("iat_vadeos_preference", "59000"));
        // 设置标点符号,设置为"0"返回结果无标点,设置为"1"返回结果有标点
        mIat.setParameter(SpeechConstant.ASR_PTT, mSharedPreferences.getString("iat_punc_preference", "1"));
        // 设置音频保存路径，保存音频格式支持pcm、wav，设置路径为sd卡请注意WRITE_EXTERNAL_STORAGE权限
        // 注：AUDIO_FORMAT参数语记需要更新版本才能生效
        mIat.setParameter(SpeechConstant.AUDIO_FORMAT, "wav");
        //String path = Environment.getExternalStorageDirectory() + "/msc/" + DateUtil.getCurrentDateStr() + ".wav";
        mIat.setParameter(SpeechConstant.ASR_AUDIO_PATH, AUDIO_SAVE_PATH);

    }


}
